package com.teaphy.readlist.controller;

import com.teaphy.readlist.model.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author teaphy
 * @desc
 * @since 15:25
 */
@Controller
// 指定加载的配置文件
@PropertySource("classpath:common.properties")
public class FileController {

    @Value("${web.file.path}")
    private String PATH;


    @RequestMapping("/openUpload")
    public String openUpload() {
        return "upload";
    }

    @RequestMapping(value = "/uploadHeader", method = RequestMethod.POST)
    @ResponseBody
    public JsonData uploadFile(@RequestParam(name = "head_image") MultipartFile file, HttpServletRequest request) {

        // 获取用户名
        String name = request.getParameter("name");
        System.out.println("用户名：" + name);

        // 获取文件名称
        String fileName = file.getOriginalFilename();
        System.out.println("文件名称：" + fileName);

        // 获取文件后缀
        String siff = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("文件后缀：" + siff);

        String fileNameSave = UUID.randomUUID().toString() + siff;
        System.out.println("保存的文件名称：" + fileNameSave);

        try {
            File dest = new File(PATH, fileNameSave);
            file.transferTo(dest);
            return new JsonData(0, fileNameSave, "success to save");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new JsonData(-1, "fail to save");
    }

}
